package cn.jiangxiong.pethome.system.login.controller;

import cn.jiangxiong.pethome.constants.BaseConstants;
import cn.jiangxiong.pethome.system.login.domian.PhoneRegister;
import cn.jiangxiong.pethome.system.user.domain.User;
import cn.jiangxiong.pethome.system.user.service.IUserService;
import cn.jiangxiong.pethome.utils.AjaxResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/register")
@Api(value = "注册API",description="注册相关的CRUD功能")
public class RegisterController {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private IUserService userService;
    @ApiOperation(value = "手机号注册")
    @PostMapping("/phone")
    public AjaxResult register(@RequestBody PhoneRegister register){
        //验证手机号是否为空
        if (register.getPhone() == null ||"".equals(register.getPhone().trim())){
            return AjaxResult.error().setMsg("手机号不能为空");
        }
        //验证手机号验证码是否为空
        if (register.getPhoneCode() == null ||"".equals(register.getPhoneCode().trim())){
            return AjaxResult.error().setMsg("手机号验证码不能为空");
        }
        // 校验两次密码是否相同 和  不为null 和““
        String password = register.getPassword();
        String passwordRepeat = register.getPasswordRepeat();
        if (password == null || "".equals(password.trim())){
            return AjaxResult.error().setMsg("密码不能为空");
        }
        if (passwordRepeat == null || "".equals(passwordRepeat.trim())){
            return AjaxResult.error().setMsg("确认密码不能为空");
        }
        if(!password.equals(passwordRepeat)){
            return AjaxResult.error().setMsg("两次密码不一致");
        }
        //验证验证码是否正确
        String key = register.getPhone()+ BaseConstants.Vcode.REGISTER;
        //还可以尝试判断key是否为空
        Object o = redisTemplate.opsForValue().get(key);

        if (o == null){
            return AjaxResult.error().setMsg("你的手机号验证码已过期");
        }
        if (register.getPhoneCode().equals(o.toString())){
            return AjaxResult.error().setMsg("手机号验证码输入错误");
        }
        User byPhone = userService.findByPhone(register.getPhone());
        if (byPhone != null){
            return AjaxResult.error().setMsg("该手机号已被注册，请登录或忘记密码");
        }
        //以上条件通过
        userService.add(register);
        return AjaxResult.success().setMsg("注册成功");
    }
}
